package com.easy.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EasyConfig {
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager getDefaultWebSecurityManager(AuthorizingRealm easyRealm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		// 关联realm
		securityManager.setRealm(easyRealm);
		return securityManager;
	}

	@Bean
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(
			@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
		// 设置安全管理器
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
		// 添加Shiro常用的过滤器
		/**
		 * 常用过滤器如下： anon：无需认证即可访问 authc：必须经过认证才能访问 user：使用记住我后可访问 perms：拥有某个资源的权限才可访问
		 * role：拥有某个角色才可访问
		 *
		 */
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap();
		filterChainDefinitionMap.put("/toindex", "authc");
		filterChainDefinitionMap.put("/easy/add", "authc");
		filterChainDefinitionMap.put("/easy/edit", "authc");
		// 支持通配符配置
//		filterChainDefinitionMap.put("/user/*", "authc");
//		// 登出
		filterChainDefinitionMap.put("/logout", "logout");
		filterChainDefinitionMap.put("/doLogin", "anon");
		filterChainDefinitionMap.put("/css/**", "anon");
		filterChainDefinitionMap.put("/**", "authc");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		// 设置登录页面，没有认证或权限的会被定位到此路径
		shiroFilterFactoryBean.setLoginUrl("/toLogin");
		return shiroFilterFactoryBean;
	}

}
